package com.software.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
    // MySQL 数据库 URL、用户名和密码
    private static final String URL ="jdbc:mysql://localhost:3306/shopadmin?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    // 静态方法用于获取数据库连接
    public static Connection getConnection() throws SQLException {
        Connection connection = null;
        try {
            // 加载 MySQL 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("MySQL 驱动加载失败！");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败！");
            throw e;
        }
        return connection;
    }

    // 可选：关闭连接的方法
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("数据库连接关闭失败！");
            }
        }
    }
}
